package admin

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/organization"

	"github.com/gin-gonic/gin"
	"github.com/lluck42/tools"
	"github.com/lluck42/tools/tree"
)

// admin 的下级 organization ids
func MyOrganizationIds(c *gin.Context, organizationId uint) (childrenIds []uint, err error) {
	// 获取登录用户对象
	var adm admin.Admin
	if err := adm.Get(c); err != nil {
		return nil, err
	}

	// 所有数据
	var loopCount uint
	var listAll []tree.Node
	if err := bean.MysqlDb.Model(&organization.Organization{}).Order("`sort` ASC").Find(&listAll).Error; err != nil {
		return nil, err
	}

	// 以传入 adm.OrganizationId 为查询根节点
	childrenIds, err = tree.TreeSelfIds(adm.OrganizationId, &listAll, &loopCount)
	if err != nil {
		return nil, err
	}

	//
	if organizationId == 0 {
		return childrenIds, nil
	}

	// 验证权限
	if !tools.InList(childrenIds, organizationId) {
		var err = fmt.Errorf("没有该组织权限id:%d", organizationId)
		return nil, err
	}

	// 以传入 organizationId 为查询根节点
	childrenIds, err = tree.TreeSelfIds(organizationId, &listAll, &loopCount)
	if err != nil {
		return nil, err
	}

	return childrenIds, nil
}
